from django.conf import settings
from django.http import HttpResponseRedirect
from urlparse import urlparse
import re


def find_destination_page(test_string):
    for (pattern, string) in settings.HELP_URL_MAPPINGS:
        if re.match(pattern, test_string):
            return string
    return ''


def redirect_to_help(request):
    referer_url = request.META.get('HTTP_REFERER', '')
    url_bits = urlparse(referer_url)
    refering_view = url_bits.path
    if refering_view[0] == '/':
        refering_view = refering_view[1:]
    destination_page = find_destination_page(refering_view)
    return HttpResponseRedirect(settings.HELP_DESTINATION_BASE_URL + destination_page) 
